package com.ruoyi.common.core.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @description Mybatis JSON映射转换处理类
 * @author lxc
 * @date 2022-04-16
 */
public class JSONHandler<T extends Object> extends BaseTypeHandler<T> {

    private Class<T> clazz;

    public JSONHandler(Class<T> clazz ){
        if (null == clazz){
            throw new IllegalArgumentException("Type argument cannot be null");
        }
        this.clazz = clazz;
    }

    private String toJson(T obj){
        return JSON.toJSONString(obj, SerializerFeature.WriteMapNullValue);
    }

    private T toObject(String jsonstr, Class<T> clazz){
        return JSON.parseObject(jsonstr,clazz);
    }

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, T t, JdbcType jdbcType) throws SQLException {
        preparedStatement.setString(i,this.toJson(t));
    }

    @Override
    public T getNullableResult(ResultSet resultSet, String s) throws SQLException {
        return this.toObject(resultSet.getString(s),clazz);
    }

    @Override
    public T getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return this.toObject(resultSet.getString(i), clazz);
    }

    @Override
    public T getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return this.toObject(callableStatement.getString(i), clazz);
    }
}
